//
//  ZCOAuthController.swift
//  weibo
//
//  Created by 张城 on 16/7/20.
//  Copyright © 2016年 张城. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZCOAuthController: UIViewController {
    
    override func loadView() {
        // https://api.weibo.com/oauth2/authorize?client_id=2485940745&redirect_uri=bd3bf273a7dc2107012ce5fc474e743c
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        
        let url = NSURL(string: urlString)
        
        guard let u = url else {
            return
        }
        
        let request = NSURLRequest(URL: u)
        
        webview.loadRequest(request)
        
        view = webview
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        
        navigationController?.view.insertSubview(progressView, belowSubview: (navigationController?.navigationBar)!)
        
        setupNav()
    }
    
    func setupNav() {
        navigationItem.title = "授权页面"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: #selector(ZCOAuthController.cancelClick))
        navigationItem.rightBarButtonItem = ZCBarButtonItem(title: "自动填充", imgName: nil, target: self, action: #selector(ZCOAuthController.autoAddClick))
    }
    
    func cancelClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoAddClick() {
//        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassword)'"
        webview.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    private lazy var webview: UIWebView = {
       let web = UIWebView()
       web.delegate = self
        return web
    }()
    
    lazy var progressView: ZCProgressView = ZCProgressView()
    
}

extension ZCOAuthController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
//        SVProgressHUD.show()
        progressView.startAnim()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
//        SVProgressHUD.dismiss()
        progressView.endAnim()
        progressView.removeProView()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlStr = request.URL?.absoluteString
        
        if let str = urlStr where str.hasPrefix(APPREDIRECT_URI) {
//            print(str)
            
            
            
            let code = str.substringFromIndex("http://www.baidu.com/?code=".endIndex)
//            print(code)
            
            ZCuserAccountViewModel.sharedTools.loadUserAccount(code, isSucess: { (isSuc) in
                print(isSuc)
                
                if !isSuc {
                    return
                }
                
//                let result = ZCuserAccountViewModel.sharedTools.userAccount
//                print(result)
                
                self.dismissViewControllerAnimated(false, completion: { 
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootNoti, object: nil)
                    
                    
                })
                
            })
            return false
        }
        

        return true
    }
}

















